/*
 * Copyright (c) 2001, 2002 Boris Pruessmann and others. All rights reserved.
 * This program and the accompanying materials are made available under the
 * terms of the Common Public License v0.5 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/cpl-v05.html
 * 
 * Contributors: Boris Pruessmann - Initial implementation.
 */
package net.sourceforge.perforce.api.internal;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Wrapper class for Perforce API SpecData class.
 * 
 * @version $Revision: 488 $
 * @author <a href="mailto:bpruessmann@users.sourceforge.net>Boris
 *         Pruessmann</a>
 */
public final class SpecData {

  /**
   * Used to store the native reference. <br>
   * DON'T TOUCH THE CONTENT OF THIS VARIABLE
   */
  @SuppressWarnings("unused")
  private int _nativeHandle;

  /** Constructor for SpecData. */
  public SpecData() {
    construct();
  }

  @Override
  public void finalize() throws Throwable {
    // TODO: Manually destruct
    super.finalize();
    destruct();
  }

  /**
   * Returns the SpecData in form of a Map.
   * 
   * @return SpecData as Map.
   */
  public native Map<String, String> getSpecDataMap();

  /**
   * Returns the value associated with the given key.
   * 
   * @param key used for lookup.
   * @return the associated value.
   */
  public native String get(String key);

  public String[] getArray(String key) {

    List<String> items = new ArrayList<String>();

    int i = 0;
    boolean hasMore = true;
    do {
      String item = get(key + i++);
      if ("".equals(item)) //$NON-NLS-1$
      {
        hasMore = false;
      } else {
        items.add(item);
      }
    } while (hasMore);

    return items.toArray(new String[items.size()]);

  }

  /**
   * Replaces the value for the given key.
   * 
   * @param key the key.
   * @param value the value.
   */
  public native void replace(String key, String value);

  /**
   * Called by the constructor to initialize the native side of this class.
   */
  private native void construct();

  /**
   * Called by finalize() to destroy the native side of this class.
   */
  private native void destruct();

  public void replace(String key, String[] values, int originalCount) {

    for (int i = 0; i < values.length; i++) {
      replace(key + i, values[i]);
    }

    for (int i = values.length, length = originalCount; i < length; i++) {
      replace(key + i, ""); //$NON-NLS-1$
    }
  }
}
